package com.pucheng.bracelet.app.service

import android.app.Service
import android.content.Intent
import android.os.IBinder
import androidx.core.app.JobIntentService
import com.blankj.utilcode.util.LogUtils
import com.clj.fastble.exception.BleException
import com.pucheng.bracelet.app.ble.BleCmd
import com.pucheng.bracelet.app.ble.BleWriteAndNotifyCallback
import com.pucheng.bracelet.app.ble.ClientManager
import com.pucheng.bracelet.app.network.apiService
import com.pucheng.bracelet.app.network.stateCallback.ListDataUiState
import com.pucheng.bracelet.app.util.ByteUtils
import com.pucheng.bracelet.app.util.CacheUtil
import com.pucheng.bracelet.ui.adapter.WatchData
import io.reactivex.Observable
import io.reactivex.disposables.Disposable
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import me.hgj.jetpackmvvm.ext.executeResponse
import me.hgj.jetpackmvvm.ext.request
import me.hgj.jetpackmvvm.ext.util.loge
import me.hgj.jetpackmvvm.network.ExceptionHandle
import java.util.concurrent.TimeUnit

internal class SyncDataService : Service() {
    var disposable: Disposable? = null
    override fun onBind(intent: Intent): IBinder? {
        return null
    }


    override fun onCreate() {
        super.onCreate()
        if (CacheUtil.isCheckWeather()) {
            if (disposable == null) {
                disposable = Observable.interval(0, 2, TimeUnit.HOURS)
                    .map { aLong: Long ->
                        LogUtils.e("第" + aLong + "次查询天气并上报")
                        queryWeather()
                        true
                    }
                    .subscribe { isConnected: Boolean? -> }
            }
        }
    }

    private fun queryWeather() {
        val city = CacheUtil.getCityInfo()
        val locationCity = CacheUtil.getLocationCityInfo()
        GlobalScope.launch { runCatching { apiService.getWeather(locationCity.country,city.name,locationCity.lat,locationCity.lon) }.onSuccess {
            runCatching {
                //校验请求结果码是否正确，不正确会抛出异常走下面的onFailure
                executeResponse(it) { t ->
                    LogUtils.e("获取天气成功：$t")
                    //{"value":1,"weather":"雷阵雨","min_tem":"27","max_tem":"31","win":"南","win_speed":"4","date":"2021-05-28"}
                    val sb = StringBuffer()
                    sb.append(BleCmd.SYNC_WEATHER)
                    //1B 0表示用华氏度显示  1表示用摄氏度显示  app传送给手环的数据都是摄氏度， 手环自行换
                    sb.append("01")
                    for (weatherInfoBean in t) {
                        //天气类型 0：表示无数据 1：晴  2：阴天  3：雨  4：雪 5：雾  6：雷雨
                        sb.append(ByteUtils.intToHexByLength(weatherInfoBean.value,1))
                        sb.append(ByteUtils.intToHexByLength(weatherInfoBean.min_tem.toInt(),1))
                        sb.append(ByteUtils.intToHexByLength(weatherInfoBean.max_tem.toInt(),1))
                    }
                    ClientManager.getInstance().sendControlCmd(sb.toString(),object :BleWriteAndNotifyCallback(){
                        override fun onCharacteristicChanged(data: ByteArray?) {

                        }

                        override fun onWriteSuccess(
                            current: Int,
                            total: Int,
                            justWrite: ByteArray?
                        ) {
                        }

                        override fun onWriteFailure(exception: BleException?) {
                        }
                    })
                }
            }.onFailure { e ->
                //打印错误消息
                LogUtils.e("获取天气失败："+e.message)
                //失败回调
//                error(ExceptionHandle.handleException(e))
            }
        }.onFailure {

            //打印错误消息
            LogUtils.e("获取天气失败："+it.message)
            //失败回调
//            error(ExceptionHandle.handleException(it))
        } }
    }
}